package com.honghu.cloud.tools;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_core.IplImage;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameConverter;

import com.honghu.cloud.utils.Exceptions;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class VideoFrameUtils {

	/*public static void main(String[] args) throws Exception {
		randomGrabberFFmpegImage("C:\\Users\\Administrator\\Desktop\\image\\aa.mp4", "C:\\Users\\Administrator\\Desktop\\file", "file3.jpg");
	}*/
	
	/**
	   * @param videoFullPath 视频全路径
	   * @param imageFolder 第一帧图片存储位置
	   * @param imageName 图片名称
	   * @throws Exception
	   */
	public static String randomGrabberFFmpegImage(String videoFullPath, String imageFolder, String imageName) throws Exception {
		File videoFullfile = new File(videoFullPath);
		if (!videoFullfile.exists()) {
			return "视频文件不存在";
		}
		File imagePath = new File(imageFolder);
		if(!imagePath.exists()){
			imagePath.mkdirs();
		}
		FFmpegFrameGrabber ff = null;
		try {
			// ff = FFmpegFrameGrabber.createDefault(videoFullfile); // 构建太慢
			ff = new FFmpegFrameGrabber(videoFullfile);
			ff.start();
			int length = ff.getLengthInFrames();
			IplImage src = null;
			String rotate =ff.getVideoMetadata("rotate");
			Frame frame = null;
			int flag  = 0;
			while (flag < length) {
				frame = ff.grabImage();
				// 旋转角度的
				if(null !=rotate && rotate.length() > 1) {
	                OpenCVFrameConverter.ToIplImage converter =new OpenCVFrameConverter.ToIplImage();
	                src =converter.convert(frame);
	                frame =converter.convert(rotate(src, Integer.valueOf(rotate)));
	            }
				// 过滤前3帧，避免出现全黑图片
			    if ((flag>3)&&(frame != null)) {
			        break;
			    }
				flag++;
			}
			doExecuteFrame(frame, imageFolder, imageName);
			ff.stop();
		} catch (Exception e) {
			log.error("生成第一帧失败："+Exceptions.getStackTraceAsString(e));
			return "生成第一帧失败，请联系管理员";
		}finally {
			if(ff != null){
				ff.close();
			}
			if(ff != null){
				try {
					ff.stop();
				} catch (Exception e) {
					log.error("视频第一帧关闭Frame失败："+Exceptions.getStackTraceAsString(e));
				}
			}
		}
		return "";
	}

	public static void doExecuteFrame(Frame f, String targerFilePath, String targetFileName) throws IOException {
		if (null == f || null == f.image) {
			return;
		}
		Java2DFrameConverter converter = new Java2DFrameConverter();
		String FileName = targerFilePath + File.separator + targetFileName;
		BufferedImage bi = converter.getBufferedImage(f);
		File output = new File(FileName);
		ImageIO.write(bi, "jpg", output);
	}
	
	/*
     * 旋转角度的
     */
    public static IplImage rotate(IplImage src, int angle) {
        IplImage img = IplImage.create(src.height(), src.width(), src.depth(), src.nChannels());
        opencv_core.cvTranspose(src, img);
        opencv_core.cvFlip(img, img, angle);
        return img;
    }

}
